package com.study.zzedu.ui.study;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.dreamfish.record.FileUtil;
import com.study.zzedu.R;
import com.study.zzedu.adapter.TabAdapter;
import com.study.zzedu.base.BaseActivity;
import com.study.zzedu.entity.NoticeItem;
import com.study.zzedu.fragment.tab.notice.CourseNoticeFragment;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.LogUtil;
import com.study.zzedu.utils.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;

/**
 * Created by kiros on 2020/9/5.
 */

public class StudyActivity extends BaseActivity {
    private XTabLayout tabLayout;
    private ViewPager viewPager;
    private List<String> list;

    private JSONArray videoArray = new JSONArray();
    private String zyh = "", dqwz = "";//资源号，播放位置
    private String lessonName, score, examType, totalHour;
    private Timer timer;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if (videoArray.length() < 1)
                return;
            try {
                JSONObject job = new JSONObject();
                job.put("msg", videoArray);

                submitData(StudyActivity.this, job.toString());
                videoArray = new JSONArray("[]");
            } catch (Exception e) {
                e.toString();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_study);

        Intent intent = getIntent();
        AppConstant.courseCode = intent.getStringExtra("courseCode");

        lessonName = intent.getStringExtra("lessonName");
        AppConstant.lessonName = lessonName;
        score = intent.getStringExtra("score");
        examType = intent.getStringExtra("examType");
        totalHour = String.valueOf(intent.getIntExtra("totalHour", 0));

        /*初始化界面*/
        initViews();
        /*初始化数据*/
        initData();
        /*设置Adapter*/
        viewPager.setAdapter(new TabAdapter(getSupportFragmentManager(), list));
        /*Tab与ViewPager绑定*/
        tabLayout.setupWithViewPager(viewPager);

        setTitleBlue("");

        if ("course".equals(intent.getStringExtra("from"))) {
            online_test.setVisibility(View.VISIBLE);
            tv_credit.setVisibility(View.VISIBLE);
        } else {
            online_test.setVisibility(View.GONE);
            tv_credit.setVisibility(View.GONE);
        }

        CourseNoticeFragment.setOnNoticeCountChange(new CourseNoticeFragment.OnCountChange() {
            @Override
            public void onChange(boolean unRead) {
                if (!unRead) {
                    tv_notice_count.setVisibility(View.VISIBLE);
                } else {
                    tv_notice_count.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        isHeadUnReadInfo();
        castFlag = false;
        if (timer == null) {
            timer = new Timer();
            timer.schedule(task, 120000, 120000);
        }
    }

    /*初始化数据*/
    private void initData() {
        list = new ArrayList<>();
        list.add("课程目录");
        list.add("在线测试");
        list.add("在线讨论");
        list.add("课程公告");

        tv_course_title.setText(lessonName);
        tv_credit.setText(score + "学分");
        online_test.setText(examType);
        lesson_time.setText(totalHour + "课时");

        getVideoDomainList();
    }

    NetworkChangeReceiver locatiopnBroadcast;
    private TextView tv_course_title, tv_notice_count, tv_credit, online_test, lesson_time;

    /*初始化界面*/
    private void initViews() {
        viewPager = findViewById(R.id.viewpager);
        tabLayout = findViewById(R.id.tab);
        tv_notice_count = findViewById(R.id.tv_notice_count);
        tv_course_title = findViewById(R.id.tv_course_title);
        tv_credit = findViewById(R.id.tv_credit);
        online_test = findViewById(R.id.online_test);
        lesson_time = findViewById(R.id.lesson_time);

        locatiopnBroadcast = new NetworkChangeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        // 2. 设置接收广播的类型
        intentFilter.addAction("com.zzu.edu.videoinfo");
        intentFilter.addAction("com.zzu.edu.audiorecord");
        intentFilter.addAction("com.zzu.edu.videoEnd");

        // 3. 动态注册：调用Context的registerReceiver（）方法
        registerReceiver(locatiopnBroadcast, intentFilter);
    }


    class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals("com.zzu.edu.videoinfo")) {
                if (!castFlag)
                    return;


                String bean = intent.getStringExtra("content");
                //JSONObject o = new JSONObject(bean);
                try {
                    JSONObject job = new JSONObject(bean);

                    videoArray.put(job);
                    //LogUtil.e("player","...............................videoMap..."+videoMap.size());
                } catch (Exception e) {
                    e.toString();
                }
            } else if (intent.getAction().equals("com.zzu.edu.videoEnd")) {
                if (task != null)
                    task.run();
            } else if (intent.getAction().equals("com.zzu.edu.audiorecord")) {
                List<File> list = FileUtil.getPcmFiles();
                if (list != null) {
                    try {
                        ResponseBody responseBody = OkHttpUtils.getInstance(context).upload(OkHttpUtils.BASE_URL + "/keChengBiJi/insertVoice", new String[]{"kch", "zyh"}, new String[]{AppConstant.courseCode, AppConstant.contentCode}, list.get(0));
                        String lk = "";
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void submitData(Context context, final String json) {
        //播放记录  kch:课程号集，zyh:资源号集，type：动作类型集（01：开始，02：播放中，03：暂停，04：拖拽，05：停止，06：倍速播放中，07：快进，08：全屏），dqwz：当前播放位置集，bfbl：播放比例集
        //LogUtil.e("Forget", "视频播放记录数据提交:" + json);
        OkHttpUtils.getInstance(context).postJson(OkHttpUtils.BASE_URL + "/message/send", json, new OkHttpUtils.HttpCallBack() {
            @Override
            public void onSuccess(String obj) {
                try {
                    JSONObject jObject = new JSONObject(obj);
                    if (0 == jObject.getInt("code")) {
                        LogUtil.e("Forget", "视频播放记录提交成功.提交数据：" + json);
                    } else {
                        LogUtil.e("Forget", "视频播放记录提交失败 提交数据：" + json);
                    }
                } catch (Exception e) {
                    e.toString();
                }
            }

            @Override
            public void onSuccess(JSONObject obj) {
                //resultListener.onSuccess(obj.toString());
            }

            @Override
            public void onError(String msg) {
                LogUtil.e("Forget", "视频播放记录提交失败");
            }
        });
    }

    private void isHeadUnReadInfo() {
        OkHttpUtils.getInstance(StudyActivity.this).getJsonForString(OkHttpUtils.BASE_URL + "/appCourseNotice/queryCourseNotice",
                new String[]{"courseCode"}, new String[]{AppConstant.courseCode}, new OkHttpUtils.HttpCallBack() {
                    @Override
                    public void onSuccess(String obj) {
                        try {
                            JSONObject jObject = new JSONObject(obj);
                            if (0 == jObject.getInt("code")) {
                                //LogUtil.e("Forget", "查询课程公告信息成功");
                                JSONArray jArray = jObject.getJSONArray("data");
                                for (int i = 0; i < jArray.length(); i++) {
                                    if (0 == jArray.getJSONObject(i).getInt("status")) {
                                        tv_notice_count.setVisibility(View.VISIBLE);
                                        return;
                                    } else {
                                        tv_notice_count.setVisibility(View.INVISIBLE);
                                    }
                                }
                            } else {
                                LogUtil.e("Forget", "查询课程公告信息失败");
                            }
                        } catch (Exception e) {
                            e.toString();
                        }
                    }

                    @Override
                    public void onSuccess(JSONObject obj) {
                        //resultListener.onSuccess(obj.toString());
                    }

                    @Override
                    public void onError(String msg) {
                        LogUtil.e("Forget", "查询课程公告信息失败");
                    }
                });
    }


    //获得视频服务主机地址数组
    private void getVideoDomainList() {
        OkHttpUtils.getInstance(StudyActivity.this).getJsonForString(OkHttpUtils.BASE_URL + "/appCourseSubject/getVideoDomainList",
                null, null, new OkHttpUtils.HttpCallBack() {
                    @Override
                    public void onSuccess(String obj) {
                        try {
                            JSONObject jObject = new JSONObject(obj);
                            if (0 == jObject.getInt("code")) {
                                LogUtil.e("Forget", "查询视频播放域名列表成功");
                                AppConstant.domainList = jObject.getJSONArray("data");
                            } else {
                                LogUtil.e("Forget", "查询视频播放域名列表失败");
                            }
                        } catch (Exception e) {
                            e.toString();
                        }
                    }

                    @Override
                    public void onSuccess(JSONObject obj) {
                        //resultListener.onSuccess(obj.toString());
                    }

                    @Override
                    public void onError(String msg) {
                        LogUtil.e("Forget", "查询视频播放域名列表失败");
                    }
                });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean castFlag = false;

    @Override
    protected void onPause() {
        super.onPause();
        castFlag = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locatiopnBroadcast != null)
            unregisterReceiver(locatiopnBroadcast);

        if (timer != null)
            timer.cancel();
    }
}
